package ldh.im.fxbase.util;

import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class GifUtil {

    public static void createGif(String outFile, List<BufferedImage> frames, int delay) throws IOException {
        // 设置GIF编码参数
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("gif");
        if (!writers.hasNext()) {
            throw new IllegalStateException("No writers found");
        }
        ImageWriter writer = writers.next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setDestinationType(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB));
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        //设置高质量压缩
        if (param.canWriteCompressed()) {
            String[] cs = param.getCompressionTypes();
            param.setCompressionType(cs[0]);
            param.setCompressionQuality(1.0f);
        }
         // 设置延迟时间（以毫秒为单位）
        IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frames.get(0).getColorModel(), frames.get(0).getSampleModel()), param);
        String metaFormatName = metadata.getNativeMetadataFormatName();
        IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(metaFormatName);

        // 设置全局延迟时间
        IIOMetadataNode graphicsControlExtension = new IIOMetadataNode("GraphicControlExtension");
        graphicsControlExtension.setAttribute("disposalMethod", "none"); // 恢复前一帧
        graphicsControlExtension.setAttribute("delayTime", Integer.toString(delay)); // 延迟时间（以1/100秒为单位）
        graphicsControlExtension.setAttribute("transparentColorIndex", "0"); // 透明色索引，如果有的话
        graphicsControlExtension.setAttribute("userInputFlag", "false");
        graphicsControlExtension.setAttribute("transparentColorFlag", "false");

        root.appendChild(graphicsControlExtension);
        metadata.setFromTree(metaFormatName, root);


        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(outFile));
        try {
            writer.setOutput(ios);
            writer.prepareWriteSequence(null);

            // 写入GIF帧
            for (BufferedImage frame : frames) {
                writer.writeToSequence(new javax.imageio.IIOImage(frame, null, null), null);
            }
            // 完成GIF编码并关闭流
            writer.endWriteSequence();
        } finally {
            if (ios != null) {
                ios.close();
            }
        }
    }
}
